package com.tudouji.common.utils.xml;

import com.alibaba.fastjson.JSONObject;
import com.tudouji.common.utils.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Iterator;

/**
 * @Author shaodong
 * @Description xml工具类
 * @Date 15:15 2021/1/26
 * @Param
 * @return
 **/
public class XmlUtils {

    /**
     * @Author shaodong
     * @Description 解析金蝶返回的XML数据
     * @Date 15:15 2021/1/26
     * @xml 返回的XML字符串
     * @keyArr 想要获取的字段键值
     * @return
     **/
    public static JSONObject getXmlAttribute(String xml, String[] keyArr) {
        Document doc = null;
        JSONObject jsonObject= new JSONObject();
        try {
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
            Element dataHead = rootElt.element("DataHead");
            setXmlData(keyArr, jsonObject, dataHead);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    private static void setXmlData(String[] keyArr, JSONObject jsonObject, Element dataHead) throws Exception{
        Iterator heads = dataHead.elementIterator();
        while (heads.hasNext()) {
            Element itemAtr = (Element) heads.next();
            if (keyArr.length > 0){
                for (int i = 0; i < keyArr.length; i++) {
                    if (StringUtils.equals(keyArr[i], itemAtr.getName())){
                        jsonObject.put(keyArr[i], itemAtr.getData());
                    }
                }
            }
        }
    }

    public static void main(String[] agrs){
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><DataInfo><DataHead><isMultiCopy>0</isMultiCopy><country/><parent/><namePinYin/><city/><oldNumber/><usedStatus>1</usedStatus><description/><industry/><isOuter>0</isOuter><isInternalCompany>0</isInternalCompany><number>02.02.0017</number><freezeOrgUnit/><isCarrier>0</isCarrier><adminCU>01</adminCU><province/><foreignName/><internalProfitCenter/><mnemonicCode/><GSPAuthentication/><effectedStatus>2</effectedStatus><taxData/><creator>user</creator><address/><busiExequatur/><taxPayerType/><bizRegisterNo/><browseGroup>02.02</browseGroup><bizAnalysisCode/><nameShortPinYin/><internalSupplierType>0</internalSupplierType><version>0</version><artificialPerson/><barCode/><taxRegisterNo/><taxRate>0E-10</taxRate><CU>01</CU><internalCompany/><createTime>2020-09-02 09:26:05</createTime><simpleName/><busiLicence/><name>山东高密佳怡包装有限公司</name><lastUpdateUser>user</lastUpdateUser><region/><lastUpdateTime>2020-09-10 19:36:23</lastUpdateTime></DataHead><DataEntries><entry><supplierGroup>02.02</supplierGroup><supplierGroupStandard>supplierGroupStandard</supplierGroupStandard><supplierGroupFullName/><supplier>02.02.0017</supplier></entry></DataEntries></DataInfo>";
        JSONObject result = getXmlAttribute(xml, new String[]{"name"});
        System.out.println(result.get("name"));
    }
}
